package com.search_wheel.controller;

import com.search_wheel.pojo.dto.AiExplanation;
import com.search_wheel.pojo.entity.Content;
import com.search_wheel.pojo.entity.User;
import com.search_wheel.pojo.vo.SearchResult;
import com.search_wheel.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private UserService userService;

    @Autowired
    private SearchHistoryService searchHistoryService;

    @Autowired
    private SearchCorrectionService searchCorrectionService;

    @Autowired
    private AiService aiService;

    /**
     * 搜索首页
     */
    @GetMapping("/")
    public String index(HttpSession session, Model model) {
        // 获取搜索历史记录
        List<String> searchHistory = searchHistoryService.getSearchHistory(session);
        model.addAttribute("searchHistory", searchHistory);
        return "search";
    }

    /**
     * 搜索页面
     */
    @GetMapping("/search")
    public String search(@RequestParam(value = "keyword", required = false) String keyword,
                         @RequestParam(value = "type", defaultValue = "all") String type,
                         @RequestParam(value = "page", defaultValue = "1") int page,
                         @RequestParam(value = "size", defaultValue = "4") int size,
                         @RequestParam(value = "sort", defaultValue = "time") String sort, // 新增sort参数
                         HttpSession session,
                         Model model) {

        // 获取搜索历史记录
        List<String> searchHistory = searchHistoryService.getSearchHistory(session);
        model.addAttribute("searchHistory", searchHistory);

        if (!StringUtils.hasText(keyword)) {
            model.addAttribute("keyword", "");
            return "search";
        }

        // 添加到搜索历史记录
        searchHistoryService.addSearchHistory(session, keyword);

// 异步获取AI解释（不阻塞主搜索流程）
        System.out.println("=== 开始AI解释请求，关键词: " + keyword + " ===");
        try {
            // 先检查AI服务是否正常注入
            if (aiService == null) {
                System.err.println("ERROR: aiService 为空！");
                model.addAttribute("aiExplanation", AiExplanation.error(keyword, "AI服务未初始化"));
            } else {
                System.out.println("AI服务注入成功，开始异步请求...");

                CompletableFuture<AiExplanation> future = aiService.getExplanationAsync(keyword);
                System.out.println("异步任务创建成功，开始等待结果...");

                AiExplanation aiExplanation = future.get(5, TimeUnit.SECONDS);
                System.out.println("AI解释结果: success=" + aiExplanation.isSuccess() +
                        ", explanation=" + aiExplanation.getExplanation() +
                        ", error=" + aiExplanation.getErrorMessage());

                model.addAttribute("aiExplanation", aiExplanation);
            }
        } catch (TimeoutException e) {
            System.err.println("AI请求超时: " + e.getMessage());
            model.addAttribute("aiExplanation", AiExplanation.error(keyword, "AI请求超时"));
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("AI解释异常: " + e.getClass().getSimpleName() + " - " + e.getMessage());
            model.addAttribute("aiExplanation", AiExplanation.error(keyword, "AI解释服务异常: " + e.getMessage()));
            e.printStackTrace();
        }
        System.out.println("=== AI解释请求完成 ===");

        // 执行搜索（传递sort参数）
        SearchResult<?> searchResult = searchService.searchByType(keyword, type, page, size, sort);

        // 分离不同类型的结果
        List<Content> contentResults = new ArrayList<>();
        List<User> userResults = new ArrayList<>();

        if (searchResult != null && searchResult.getData() != null) {
            for (Object item : searchResult.getData()) {
                if (item instanceof Content) {
                    contentResults.add((Content) item);
                } else if (item instanceof User) {
                    userResults.add((User) item);
                }
            }
        }

        // 设置模板变量
        model.addAttribute("keyword", keyword);
        model.addAttribute("type", type);
        model.addAttribute("searchResult", searchResult);
        model.addAttribute("contentResults", contentResults);
        model.addAttribute("userResults", userResults);

        // 分页相关
        model.addAttribute("totalCount", searchResult != null ? searchResult.getTotal() : 0);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);

        int totalCount = searchResult != null ? (int) searchResult.getTotal() : 0;
        int totalPages = (int) Math.ceil((double) totalCount / size);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("hasPrevious", page > 1);
        model.addAttribute("hasNext", page < totalPages);

        // 将排序参数传递给前端
        model.addAttribute("sort", sort);

        return "search";
    }

    /**
     * 异步获取AI解释的AJAX接口
     */
    @GetMapping("/search/ai-explanation")
    @ResponseBody
    public AiExplanation getAiExplanation(@RequestParam("keyword") String keyword) {
        if (!StringUtils.hasText(keyword)) {
            return AiExplanation.error(keyword, "关键词不能为空");
        }

        try {
            return aiService.getExplanationAsync(keyword)
                    .get(8, TimeUnit.SECONDS); // AJAX请求可以等待更久一些
        } catch (Exception e) {
            return AiExplanation.error(keyword, "获取AI解释失败: " + e.getMessage());
        }
    }


    @GetMapping("/search/suggestions")
    @ResponseBody
    public List<String> getSearchSuggestions(@RequestParam("keyword") String keyword,
                                             HttpSession session) {
        if (!StringUtils.hasText(keyword) || keyword.length() < 1) {
            return new ArrayList<>();
        }

        List<String> suggestions = new ArrayList<>();

        // 添加纠错建议
        List<String> corrections = searchCorrectionService.getCorrectionSuggestions(keyword, session);
        suggestions.addAll(corrections);

        // 从搜索历史中获取匹配的建议
        suggestions.addAll(searchHistoryService.getSearchSuggestions(session, keyword));

        // 添加基于内容的建议
        suggestions.addAll(contentService.getContentTitlesContaining(keyword, 3));

        // 添加基于用户的建议
        suggestions.addAll(userService.getUsernamesContaining(keyword, 2));

        // 去重并限制数量
        return suggestions.stream()
                .distinct()
                .limit(10)
                .collect(Collectors.toList());
    }

    @GetMapping("/search/correction")
    @ResponseBody
    public Map<String, Object> checkCorrection(@RequestParam("keyword") String keyword,
                                               HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        if (searchCorrectionService.needsCorrection(keyword, session)) {
            List<String> suggestions = searchCorrectionService.getCorrectionSuggestions(keyword, session);
            result.put("needsCorrection", true);
            result.put("suggestions", suggestions);
            if (!suggestions.isEmpty()) {
                result.put("message", "您是否要搜索：" + String.join("、", suggestions.subList(0, Math.min(3, suggestions.size()))) + "？");
            }
        } else {
            result.put("needsCorrection", false);
        }

        return result;
    }

    /**
     * 清空搜索历史记录
     */
    @PostMapping("/search/history/clear")
    @ResponseBody
    public String clearSearchHistory(HttpSession session) {
        searchHistoryService.clearSearchHistory(session);
        return "success";
    }

    /**
     * 删除单个搜索历史记录
     */
    @PostMapping("/search/history/remove")
    @ResponseBody
    public String removeSearchHistory(@RequestParam("keyword") String keyword,
                                      HttpSession session) {
        searchHistoryService.removeSearchHistory(session, keyword);
        return "success";
    }

    /**
     * 内容详情页
     */
    @GetMapping("/content/{id}")
    public String contentDetail(@PathVariable("id") Integer id, Model model) {
        Content content = contentService.getContentDetail(id);

        if (content == null || content.getStatus() != 1) {
            return "error/404";
        }

        model.addAttribute("content", content);
        return "content";
    }

    /**
     * 用户详情页
     */
    @GetMapping("/user/{id}")
    public String userDetail(@PathVariable("id") Integer id, Model model) {
        User user = userService.getUserDetail(id);

        if (user == null || user.getStatus() != 1) {
            return "error/404";
        }

        model.addAttribute("user", user);
        return "user";
    }
}